package com.langyiquan.service.impl;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.langyiquan.config.AliOssResource;
import com.langyiquan.exception.http.UploadException;
import com.langyiquan.service.ResourceService;
import org.n3r.idworker.Sid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

public class AliOssResourceImpl implements ResourceService {

    @Autowired
    private AliOssResource aliOssResource;

    @Autowired
    public Sid sid;

    final static Logger logger = LoggerFactory.getLogger(AliOssResourceImpl.class);

    @Override
    public String uploadFile(MultipartFile file, String category) {

        //创建OSSClient实例
        OSSClient ossClient = new OSSClient(aliOssResource.getEndpoint(), aliOssResource.getAccessKeyId(), aliOssResource.getAccessKeySecret());
        try {
            String fileName = file.getOriginalFilename();
            String fileNameArr[] = fileName.split("\\.");
            String suffix = fileNameArr[fileNameArr.length - 1];

            String ossFileName = sid.nextShort();
            String dateDir = new SimpleDateFormat("yyyyMMdd").format(new Date()).toString();
            ossFileName =  category + "/" + dateDir + "/" + ossFileName+'.'+ suffix;
            InputStream inputStream = file.getInputStream();
            PutObjectResult result = ossClient.putObject(aliOssResource.getBucket(), ossFileName, inputStream);
            return aliOssResource.getBucketUrl() + "/" +ossFileName;
        } catch (Exception e) {
            throw new UploadException(9001);
        } finally {
            ossClient.shutdown();
        }

    }


}
